package com.zlp.feign;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.zlp.config.oss.OssTemplate;
import com.zlp.dto.UploadResp;
import com.zlp.utils.ConstantsUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j(topic = "FileUploadFeignImpl")
@Api(value = "UserFeign", tags = "用户Feign")
public class FileUploadFeignImpl implements FileUploadFeign {

    @Resource
    private OssTemplate ossTemplate;
    //目前所有文件都存放在该命名空间下
    private final static String BucketName = "greenvalley";

    @Override
    public UploadResp uploadFile(MultipartFile file, String type) {

        log.info("uploadFile.req type={}",type);
        UploadResp uploadResp = new UploadResp();
        String originalFilename = file.getOriginalFilename();
        uploadResp.setFileName(originalFilename);
        String filePath = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(originalFilename);
        if (!StringUtils.isEmpty(type)) {
            filePath = type + StrUtil.SLASH + filePath;
        }
        try {
            ossTemplate.putObject(BucketName, filePath, file.getInputStream());
            String fileUrl = ConstantsUtil.HTTP_PREFIX + BucketName + StrUtil.DOT + ConstantsUtil.DOMAIN + StrUtil.SLASH + filePath;
            uploadResp.setFileUrl(fileUrl);
            return uploadResp;
        } catch (Exception e) {
            log.error("上传失败", e);
        }
        return null;
    }

    @Override
    public List<UploadResp> uploadFiles(MultipartFile[] files, String type) {

        List<UploadResp> uploadRespList = new ArrayList<>();
        for (MultipartFile file : files) {
            uploadRespList.add(this.uploadFile(file,type));
        }
        return uploadRespList;
    }
}
